package com.jieshao.actions

import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.components.service
import com.intellij.openapi.project.DumbAwareAction
import com.jieshao.service.LineShareRuntime
import com.jieshao.utils.LineShareBundle

class LineShareAction : DumbAwareAction() {

    override fun actionPerformed(e: AnActionEvent) {

        val project = e.project ?: return

        val runtime = project.service<LineShareRuntime>()

        runtime.getSelectInfo()

        runtime.doProcess()
    }

    init {
        templatePresentation.text = LineShareBundle.message("action.LineShare.name")
    }

    /**
     * 检查是否使用git仓库，并决定按钮是否可用
     */
    override fun update(e: AnActionEvent) {
        try {
            super.update(e)

            e.presentation.isEnabled = e.project != null

            val project = e.project ?: return
            val runtime = project.service<LineShareRuntime>()
            val rule = runtime.rule ?: run {
                e.presentation.isEnabledAndVisible = false
                return@update
            }

            // 如果非项目文件
            if (!runtime.isInLocalFileSystem()){
                e.presentation.isEnabled = false
                return
            }

            e.presentation.isEnabledAndVisible = true
            if (null != rule.icon) {
                e.presentation.icon = rule.icon
            }
        } catch (exception: Exception) {
            e.presentation.isEnabledAndVisible = false
        }
    }

    override fun getActionUpdateThread(): ActionUpdateThread {
        return ActionUpdateThread.BGT
    }
}